# Copyright (c) 2013, 2015 Ruslan Baratov
# All rights reserved.

cmake_minimum_required(VERSION 3.0)
project(Hunter)

include(ExternalProject) # ExternalProject_Add

list(APPEND CMAKE_MODULE_PATH "@HUNTER_SELF@/cmake/modules")

include(hunter_fatal_error)
include(hunter_status_debug)
include(hunter_assert_not_empty_string)

hunter_status_debug("Scheme: url_sha1_ios_sim")

# Check preconditions
hunter_assert_not_empty_string("@HUNTER_SELF@")
hunter_assert_not_empty_string("@HUNTER_EP_NAME@")
hunter_assert_not_empty_string("@HUNTER_PACKAGE_URL@")
hunter_assert_not_empty_string("@HUNTER_PACKAGE_SHA1@")
hunter_assert_not_empty_string("@HUNTER_PACKAGE_DOWNLOAD_DIR@")
hunter_assert_not_empty_string("@HUNTER_PACKAGE_SOURCE_DIR@")
hunter_assert_not_empty_string("@HUNTER_PACKAGE_INSTALL_PREFIX@")
hunter_assert_not_empty_string("@HUNTER_PACKAGE_LICENSE_DIR@")
hunter_assert_not_empty_string("@HUNTER_TLS_VERIFY@")

string(COMPARE NOTEQUAL "@HUNTER_JOBS_OPTION@" "" have_jobs)
if(have_jobs)
  set(jobs_option "-jobs" "@HUNTER_JOBS_OPTION@")
else()
  set(jobs_option "")
endif()

execute_process(
    COMMAND xcrun -f clang++
    RESULT_VARIABLE result
    OUTPUT_VARIABLE compiler
    OUTPUT_STRIP_TRAILING_WHITESPACE
)

if(NOT result EQUAL 0)
  hunter_fatal_error(
      "'xcrun -f clang++' failed"
      ERROR_PAGE "error.xcrun.clang"
  )
endif()

ExternalProject_Add(
    "@HUNTER_EP_NAME@"
    URL
    @HUNTER_PACKAGE_URL@
    URL_HASH
    SHA1=@HUNTER_PACKAGE_SHA1@
    DOWNLOAD_DIR
    "@HUNTER_PACKAGE_DOWNLOAD_DIR@"
    TLS_VERIFY
    "@HUNTER_TLS_VERIFY@"
    SOURCE_DIR
    "@HUNTER_PACKAGE_SOURCE_DIR@"
    INSTALL_DIR
    "@HUNTER_PACKAGE_INSTALL_PREFIX@"
        # not used, just avoid creating Install/<name> empty directory
    CONFIGURE_COMMAND
    ""
    BUILD_COMMAND
    "CC=${compiler}" && . "@HUNTER_SELF@/scripts/clear-all.sh" &&
    xcodebuild -target ios-sim -configuration Release ${jobs_option}
    BUILD_IN_SOURCE
    1
    INSTALL_COMMAND
    "@CMAKE_COMMAND@" -E copy build/Release/ios-sim "@HUNTER_PACKAGE_INSTALL_PREFIX@"
    COMMAND # Copy license files
    "@CMAKE_COMMAND@"
    "-C@HUNTER_ARGS_FILE@" # for 'HUNTER_INSTALL_LICENSE_FILES'
    "-Dsrcdir=@HUNTER_PACKAGE_SOURCE_DIR@"
    "-Ddstdir=@HUNTER_PACKAGE_LICENSE_DIR@"
    -P
    "@HUNTER_SELF@/scripts/try-copy-license.cmake"
)
